package com.hsc.orderservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hsc.commonutils.JwtUtils;
import com.hsc.commonutils.R;
import com.hsc.orderservice.client.EduClient;
import com.hsc.orderservice.client.UcenterClient;
import com.hsc.orderservice.entity.Order;
import com.hsc.orderservice.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-10-19
 */
@RestController
//@CrossOrigin //gateway解决了可以注掉
@RequestMapping("/eduorder/order")
public class OrderController {

    @Autowired
    private OrderService orderService;


    /**
     * 创建订单
     * @param courseId 课程id
     * @param request 请求信息，token
     * @return
     */
    @PostMapping("createOrder/{courseId}")
    public R saveOrder(@PathVariable String courseId, HttpServletRequest request){
        //获取用户id
        String id = JwtUtils.getMemberIdByJwtToken(request);
        //创建订单，返回订单号
        String orderId = orderService.createOrders(courseId,id);


        return R.ok().data("orderId",orderId);
    }

    /**
     * 根据订单号查询订单信息
     * @param orderId
     * @return
     */
    @GetMapping("getOrderInfo/{orderId}")
    public R getOrderInfo(@PathVariable String orderId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderId);
        Order order = orderService.getOne(wrapper);
        return R.ok().data("item",order);
    }

    /**
     * 根据课程id与用户id判断订单是否已经下单，确认购买情况，被其它服务调用，是生产者
     * @param courseId
     * @param memberId
     * @return
     */
    @GetMapping("isBuyCourse/{courseId}/{memberId}")
    public Boolean isBuyCourse(@PathVariable String courseId,
                               @PathVariable String memberId){
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId).eq("member_id",memberId).eq("status",1);
        int count = orderService.count(wrapper);
        if(count!=0){
            return true;
        }
        return false;
    }



}

